package handler.importremotedb;

import handler.BaseHandler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.hn.comm.excel.ExcelHandler;
import com.hn.comm.excel.ExcelModel;
import com.hn.wordmemo.common.dto.BaseDTO;
import com.hn.wordmemo.webservice.IImportDBService;
import com.hn.wordmemo.wordstore.model.Book;
import com.hn.wordmemo.wordstore.model.Word;

public class ImportToRemoteDB extends BaseHandler {
	
	public static String webserviceURL="http://localhost/xfservice/IImportDBService";
	public static String webserviceService="com.hn.wordmemo.webservice.IImportDBService";

	public static void main(String[] args) {
		ImportToRemoteDB itrDB = new ImportToRemoteDB();
		ExcelModel eModel = ExcelHandler.getExcelData(BaseHandler
				.getExcelFile());
		Book book = new Book();
		book.setBooknameChinese(eModel.getBookNameChinese());
		book.setBooknameEnglish(eModel.getBookNameEnglish());
		book.setBooknameAbridge(eModel.getBooknameAbridge());
		book.setBookId(eModel.getBookID());
		book.setWordcount(eModel.getContent().size());
		book.setFree("n");

		// 导入远端数据库
		boolean isImportBook = itrDB.uploadBookToRemoteDB(book);
//		boolean isImportBook=true;

		if (isImportBook) {
			List<Word> listWord = new ArrayList<Word>();
			for (int i = 0; i < eModel.getContent().size(); i++) {
				// 如果刚满100条并且数组中有数据，那么上传到远端数据库
				if (i % 100 == 0 && listWord.size() > 0) {
					System.out.println("开始上传单词,"+(i-100)+"——>"+i);
					itrDB.uploadWordToRemoteDB(listWord);
					listWord.clear();
				}

				Map map = eModel.getContent().get(i);
				Word word = itrDB.getWordByExcelCell(eModel.getBookID(), map);
				listWord.add(word);
			}

			// 如果还有数据，那么继续上传
			if (listWord.size() > 0) {
				itrDB.uploadWordToRemoteDB(listWord);
			}
		}else
		{
			System.out.println("导入书信息失败，停止导入!");
		}
		
	}

	public boolean uploadBookToRemoteDB(Book book) {
//		XfireService xs = new XfireService();
//		xs.setUrl(webserviceURL);
//		xs.setServiceName(webserviceService);
//
//		IImportDBService iidbs = (IImportDBService) xs.getService();
//		BaseDTO baseDTO = iidbs.importBook(book);
//
//		System.out.println("上传到远程数据库书，书名:" + book.getBooknameChinese()
//				+ ",单词个数:" + book.getWordcount());
//		System.out.println("上传结果="+baseDTO.isSuccess()+",失败原因:"+baseDTO.getFailMemo());
//		return baseDTO.isSuccess();
		return true;
	}

	/**
	 * 上传到远端数据库单词
	 * 
	 * @param listWord
	 */
	public void uploadWordToRemoteDB(List<Word> listWord) {
//		XfireService xs = new XfireService();
//		xs.setUrl(webserviceURL);
//		xs.setServiceName(webserviceService);
//		IImportDBService iidbs = (IImportDBService) xs.getService();
//
//		iidbs.importWords(listWord);
//
//		System.out.println("上传到远程数据库单词，个数:" + listWord.size());
	}

}
